package utils

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"mass-user/commons/message"
	"net"
)

type Transfer struct {
	Conn net.Conn
	Buf [8096]byte

}

func (transfer Transfer) ReadPkg() (msg message.Message, err error) {
	_, err = transfer.Conn.Read(transfer.Buf[:4])
	if err != nil {
		//err = errors.New("获取头出错")
		return
	}
	//fmt.Printf("读取到%v字节数据，%v\n", n, buf[:4])
	var lenPkg uint32
	lenPkg = binary.BigEndian.Uint32(transfer.Buf[0:4])
	n, err := transfer.Conn.Read(transfer.Buf[:lenPkg])
	if n != int(lenPkg) || err != nil {
		return
	}
	err = json.Unmarshal(transfer.Buf[:lenPkg], &msg)
	if err != nil{
		err = errors.New("反序列化失败！")
		return
	}
	return
}



func (transfer Transfer) WriterData(data []byte) error {
	//发送长度给对方
	dataLen := uint32(len(data))
	binary.BigEndian.PutUint32(transfer.Buf[:4], dataLen)
	n, err := transfer.Conn.Write(transfer.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("发送失败")
		return err
	}
	transfer.Conn.Write(data)
	//defer transfer.Conn.Close()
	return nil
}

